/**
 * 首页相关API
 */
import request from '@/common/request'
import config from '@/common/config'
import mockData from '../mock/index.js'

const BASE_URL = config.apiBaseUrl

/**
 * 获取首页健康数据统计
 * @returns {Promise} 返回健康数据统计
 */
export function getHealthStats() {
  // 模拟数据
  const latestRecord = mockData.getLatestBloodSugarRecord()
  const status = latestRecord ? mockData.getBloodSugarStatus(latestRecord.value, latestRecord.type) : 'normal'
  const weeklyAvg = mockData.bloodSugarStatistics.week.average
  const dietRecords = mockData.getDietRecords()
  const exerciseRecords = mockData.getExerciseRecords()

  // 计算总步数
  const totalSteps = exerciseRecords.reduce((sum, record) => {
    return sum + (record.steps || 0)
  }, 0)
  
  // 计算运动消耗的卡路里
  const totalExerciseCalories = exerciseRecords.reduce((sum, record) => {
    return sum + (record.calories || 0)
  }, 0)

  // 计算当前服药完成情况
  const medicineReminders = mockData.reminders.filter(r => r.type === 'medicine' && r.active)
  const completedCount = mockData.getCompletedRemindersCount()
  
  return Promise.resolve({
    code: 0,
    data: {
      bloodSugar: latestRecord ? {
        latestValue: latestRecord.value,
        unit: 'mmol/L',
        timeType: latestRecord.type,
        time: latestRecord.time,
        date: latestRecord.date,
        status: status, // normal, high, low
        trend: 'stable', // up, down, stable
        weeklyAvg: weeklyAvg
      } : null,
      diet: {
        calories: dietRecords.total.calories,
        caloriesGoal: 2000,
        carbs: dietRecords.total.carbs,
        carbsGoal: 250,
        protein: dietRecords.total.protein,
        proteinGoal: 60,
        fat: dietRecords.total.fat,
        fatGoal: 60
      },
      medicine: {
        todayTaken: completedCount,
        todayTotal: medicineReminders.length,
        nextDose: medicineReminders.length > completedCount ? {
          name: medicineReminders[completedCount].title,
          time: medicineReminders[completedCount].time,
          dosage: medicineReminders[completedCount].desc
        } : null
      },
      sleep: {
        lastNight: 7.5,
        weeklyAvg: 7.2,
        quality: 'good' // good, fair, poor
      },
      exercise: {
        todaySteps: totalSteps,
        stepsGoal: 8000,
        todayCalories: totalExerciseCalories,
        weeklyAvg: 5800
      }
    }
  })
  
  // 实际接口
  // return request.get(`${BASE_URL}/home/health-stats`)
}

/**
 * 获取首页提醒事项
 * @returns {Promise} 返回提醒事项列表
 */
export function getReminders() {
  // 模拟数据
  const todayReminders = mockData.getTodayReminders().slice(0, 4)
  const completedCount = mockData.getCompletedRemindersCount()

  // 对每个提醒判断是否已完成
  const reminderList = todayReminders.map((reminder, index) => {
    return {
      id: reminder.id,
      type: reminder.type,
      title: reminder.title,
      content: reminder.desc,
      time: reminder.time,
      isComplete: index < completedCount
    }
  })
  
  return Promise.resolve({
    code: 0,
    data: reminderList
  })
  
  // 实际接口
  // return request.get(`${BASE_URL}/home/reminders`)
}

/**
 * 获取首页健康文章
 * @returns {Promise} 返回健康文章列表
 */
export function getHealthArticles() {
  // 模拟数据
  return Promise.resolve({
    code: 0,
    data: [
      {
        id: 1,
        title: '糖尿病饮食的三大误区',
        summary: '很多糖尿病患者在饮食上存在一些认识误区，本文为您一一解析...',
        coverImage: '/static/images/placeholder.png',
        author: '张医生',
        publishDate: '2023-06-15',
        viewCount: 1250
      },
      {
        id: 2,
        title: '坚持这些运动，血糖更稳定',
        summary: '适当的运动对控制血糖非常有帮助，特别是这几种运动方式...',
        coverImage: '/static/images/placeholder.png',
        author: '李医生',
        publishDate: '2023-06-12',
        viewCount: 980
      },
      {
        id: 3,
        title: '血糖监测的最佳时间点',
        summary: '合理的血糖监测时间点可以更准确地了解血糖变化情况...',
        coverImage: '/static/images/placeholder.png',
        author: '王医生',
        publishDate: '2023-06-10',
        viewCount: 1560
      }
    ]
  })
  
  // 实际接口
  // return request.get(`${BASE_URL}/home/articles`)
}

/**
 * 获取个性化健康建议
 * @returns {Promise} 返回健康建议
 */
export function getHealthAdvices() {
  // 模拟数据
  // 根据最新血糖记录生成建议
  const latestRecord = mockData.getLatestBloodSugarRecord()
  const status = latestRecord ? mockData.getBloodSugarStatus(latestRecord.value, latestRecord.type) : 'normal'
  
  let bloodSugarAdvice = {
    id: 1,
    title: '血糖控制建议',
    content: '您的血糖控制情况良好，请继续保持当前的饮食和运动习惯。',
    type: 'bloodSugar'
  }
  
  if (status === 'high') {
    bloodSugarAdvice.content = '您最近的血糖略高于正常范围，建议减少碳水化合物的摄入，增加蔬菜水果的比例。'
  } else if (status === 'low') {
    bloodSugarAdvice.content = '您最近的血糖略低于正常范围，建议适当增加主食摄入，保持规律饮食。'
  }
  
  // 运动建议
  const exerciseRecords = mockData.getExerciseRecords()
  const totalDuration = exerciseRecords.reduce((sum, record) => sum + record.duration, 0)
  
  const exerciseAdvice = {
    id: 2,
    title: '运动建议',
    content: totalDuration < 60 
      ? '您的运动量略显不足，建议每天保持30分钟以上的中等强度运动。'
      : '您的运动量符合健康标准，请继续保持！',
    type: 'exercise'
  }
  
  // 饮食建议
  const dietRecords = mockData.getDietRecords()
  const dietAdvice = {
    id: 3,
    title: '饮食建议',
    content: dietRecords.total.protein < 80
      ? '您的蛋白质摄入略低于推荐水平，可以适当增加豆类、鸡蛋和白肉的摄入。'
      : '您的饮食结构均衡，请继续保持健康的饮食习惯！',
    type: 'diet'
  }
  
  return Promise.resolve({
    code: 0,
    data: [bloodSugarAdvice, exerciseAdvice, dietAdvice]
  })
  
  // 实际接口
  // return request.get(`${BASE_URL}/home/advices`)
}

/**
 * 获取用户基本信息
 * @returns {Promise} 返回用户信息
 */
export function getUserInfo() {
  // 使用统一的用户数据
  return Promise.resolve({
    code: 0,
    data: mockData.currentUser
  })
  
  // 实际接口
  // return request.get(`${BASE_URL}/user/info`)
} 